<!--富文本-->
<template>
    <div style="height: 100%">
        <div id="RichText">
        </div>
        <div style="height: 20px;">
            <el-button type="primary" @click="getRichTextHtml">确 定</el-button>
        </div>
    </div>
</template>

<script>
import E from "wangeditor"
import {mapState} from "vuex";
import {getToken} from "@/api/auth";
import {upload} from "@/api/modules/user";
import SparkMD5 from "spark-md5";
import {insertArticle} from "@/api/modules/article";

export default {
    name: "richText",
    data() {
        return {
            //富文本框
            editor: null,
            //api
            api: this.$store.getters.app.api,
            //用户信息
            userInfo: this.$store.getters.app.userInfo,
            //上传的文件id
            uploadFileId: []
        }
    },
    created() {
    },
    async mounted() {
        await this.createRichText();
    },
    computed: {
        ...mapState({
            loginServiceApi: state => state.loginServiceApi,
        })
    },
    methods: {
        //创建富文本
        async createRichText() {
            this.editor = new E('#RichText')
            this.editor.config.height = 500;
            this.editor.config.menus = [
                'head',          //标题
                'bold',          //加粗
                'fontSize',         //字号
                'fontName',         //字体
                'italic',           //斜体
                'underline',        //下划线
                'strikeThrough',    //删除线
                'indent',           //缩进
                'lineHeight',       //行高
                'foreColor',        //文字颜色
                'backColor',        //背景色
                'link',             //连接
                'list',             //序列
                'todo',             //待办事项
                'justify',          //对其
                'quote',            //引用
                'emoticon',         //表情
                'image',            //图片
                'video',            //视频
                'table',            //表格
                'code',             //代码
                'splitLine',        //分割线
                'undo',             //撤销与回退
                'redo',             //全屏
            ]
            await this.RichTextFileUpload(this.editor)
            this.editor.create()
        },
        //新增文章
        getRichTextHtml() {
            let html = this.editor.txt.html()
            if (html) {
                let data = {
                    userid: this.userInfo.username,
                    content: html,
                    fileIds:this.uploadFileId
                }
                this.api.article.insertArticle(data).then(res => {
                    if (res.code == 200) {
                        this.$message("新增成功！")
                        // this.$emit("outRichText")
                        // res.data.adminVo = {
                        //     name: this.userInfo.name,
                        //     username: this.userInfo.username,
                        //     userFace: this.userInfo.userFace
                        // }
                        // eventBus.$emit("insertArticle", res.data)
                        // this.$message({
                        //     message: '发送成功！',
                        //     type: 'success'
                        // });
                    }
                })
            }
        },
        //图片上传
        async RichTextFileUpload() {
            let that = this;
            this.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
                //配置参数
                console.log(resultFiles)
                const formData = new FormData()
                for (let i = 0; i < resultFiles.length; i++) {
                    let file = resultFiles[i];
                    let hashValue = await imgbase(file);
                    formData.append('hashValues',hashValue )
                    console.log("dddd",file,hashValue)
                    formData.append('files', file)
                }
                //调用接口
                that.api.user.upload(formData).then(res => {
                    if (res.code === 200) {
                        for (let i = 0; i < res.data.length; i++) {
                            // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
                            insertImgFn(res.data[i].url)

                            that.uploadFileId.push(res.data[i].id)
                        }

                    }
                })

                //获取文件hash值，利用同步new Promisereader.onload，防止异步
                function imgbase(file) {
                    // new 一个Promise实例
                    return new Promise((resolve) => {
                        // 对文件对象的处理
                        let reader = new FileReader();
                        let spark = new SparkMD5.ArrayBuffer();
                        // 获取文件二进制数据
                        reader.readAsArrayBuffer(file);
                        let fileHash = null;
                        reader.onload = function (e) {
                            spark.append(e.target.result);
                            fileHash = spark.end();
                            resolve(fileHash);
                            console.log("aaaa",fileHash)
                        };
                    });
                }
            }
        }
    }
}
</script>

<style scoped>
.el-button {
    margin: 10px 0px 10px 10px;
    float: right;
}

.w-e-full-screen-editor {
    top: 0;
}
</style>
